﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MMy.Core.FrameWork.Attributes;
using My.Core.FrameWork.Auth.Policys;
using My.Core.Model;
using My.Core.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;

namespace MyCore.Api
{
    /// <summary>
    /// 登录相关
    /// </summary>
    [ActionDescriptionAttribute("Api登录")]
    [ApiController]
    [Route("api/Login")]
    public class LoginApiController : ControllerBase
    {
        /// <summary>
        /// 注入的权限对象 用户相关权限  List<PermissionItem> permissions
        /// </summary>
        public readonly PermissionRequirement _requirement;
        /// <summary>
        /// 数据库
        /// </summary>
        public MyDbContext _myDbContext;
        /// <summary>
        /// 默认构造
        /// </summary>
        /// <param name="requirement"></param>
        /// <param name="myDbContext"></param>
        public LoginApiController(PermissionRequirement requirement, MyDbContext myDbContext)
        {
            _requirement = requirement;
            _myDbContext = myDbContext;
        }



        /// <summary>
        /// 获取Token (登陆)
        /// </summary>
        /// <param name="Account">Admin</param>
        /// <param name="PassWord">123456</param>
        /// <returns></returns>
        [ActionDescriptionAttribute("获取Token (登陆)")]
        [HttpGet("OnLogin")]
        public IActionResult OnLogin(string Account, string PassWord)
        {
            //用户信息
            var userInfo = _myDbContext.FrameworkUsers.Where(x => x.Account == Account && x.PassWord == PassWord).FirstOrDefault();
            if (userInfo == null)
            {
                var responseJson = new TokenInfoViewModel
                {
                    success = false,
                    token = "",
                    expires_in = 0,
                    token_type = "Bearer",
                    msg = "用户不存在"
                };
                return new JsonResult(responseJson);
            }
            List<int> rolesId = new List<int>();
            _myDbContext.FrameworkUserRoles.Where(x => x.UserId == userInfo.Id && x.IsDeleted==false).Select(x => new { x.Id }).ToList().ForEach(x => { rolesId.Add(x.Id); });
            //用户的角色
            List<PermissionItem> list = new List<PermissionItem>();
            var RoleMenus = _myDbContext.FrameworkRoleMenuPermissions.Include(x => x.MenuItem).Where( x => x.IsDeleted==false && rolesId.Contains((int)x.RoleId)).ToList();//.Where(x =>roles.Any(c=>x.RoleId==c.Id)).ToList();
            if (RoleMenus.Count > 0)
            {
                RoleMenus.ForEach(x =>
                {
                    list.Add(new PermissionItem() { Role = x.RoleId.ToString(), Url = x.MenuItem.LinkUrl }); //添加角色和请求链接
                });
            }
            _requirement.Permissions = list;

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //这个不知道是否有问题
            //如果是基于角色的授权策略，这里要添加角色
            var claims = new List<Claim>
            {
                    new Claim(ClaimTypes.Name, userInfo.Account),
                    new Claim(JwtRegisteredClaimNames.Jti, userInfo.Id.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())
            };
            claims.AddRange(list.Select(s => new Claim(ClaimTypes.Role, s.Role)));
            //用户标识
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaims(claims);

            var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
            return new JsonResult(token);
        }
    }
}

//var claimIdentity = new ClaimsIdentity("MyCookieAuthenticationScheme");
//claimIdentity.AddClaim(new Claim(ClaimTypes.Name, "admin_1"));
//claimIdentity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
//claimIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
//claimIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin2"));
//var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
//await HttpContext.SignInAsync("MyCookieAuthenticationScheme", claimsPrincipal, new AuthenticationProperties
//{
//    ExpiresUtc = DateTime.UtcNow.AddMinutes(60),
//    IsPersistent = true,
//    AllowRefresh = false
//});
